package controller

import (
	"encoding/json"
	"fmt"
	"gin/dao"
	"gin/middleware"
	"gin/model"
	"gin/param"
	"gin/server"
	"gin/tool"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type MemberController struct {
}

func (mem *MemberController) Router(engine *gin.Engine) {
	engine.GET("/getMemberUserInfo", middleware.CheckMemberLogin(), mem.GetInfo)
	engine.GET("/api/sendSmsCode", mem.SendSmsCode)
	engine.POST("/api/memberRegister", mem.Register)
	engine.POST("/api/memberAccPassLogin", mem.AccPassLogin)
	engine.POST("/api/memberSmsLogin", mem.SmsLogin)
	engine.PUT("/api/memberInfo", mem.MemberInfo)
	engine.PUT("/api/memberEdit", middleware.CheckMemberLogin(), mem.MemberEdit)
}

func (mem *MemberController) GetInfo(c *gin.Context) {
	userId := c.GetInt("userId")
	c.JSON(200, map[string]interface{}{
		"code": 200,
		"msg":  "SUCCESS",
		"data": userId,
	})
}

//用户手机号注册
func (mem *MemberController) Register(c *gin.Context) {
	var registerParam param.RegisterParam
	if err1 := tool.Decode(c.Request.Body, &registerParam); err1 != nil {
		tool.Error(c, "参数解析失败")
	}
	service := server.MemberServer{}
	st, msg, data := service.Register(registerParam)
	if !st {
		tool.Error(c, msg)
		return
	}
	tool.Success(c, data)
	return
}

//短信发送
func (mem *MemberController) SendSmsCode(c *gin.Context) {
	mobile, exist := c.GetQuery("mobile")
	types, existType := c.GetQuery("status")
	status, stErr := strconv.Atoi(types)
	if !exist {
		tool.Success(c, "参数解析失败")
	}
	if !existType {
		tool.Success(c, "参数解析失败")
	}
	if stErr != nil {
		tool.Success(c, "参数解析失败类型转换")
	}
	service := server.MemberServer{}
	isSend, msg := service.SendCode(mobile, status)
	if !isSend {
		tool.Error(c, msg)
		return
	}
	tool.Success(c, msg)
	return
}

//账号密码登录
func (mem *MemberController) AccPassLogin(c *gin.Context) {
	var accPassLogin param.AccPassLoginParam
	if err := tool.Decode(c.Request.Body, &accPassLogin); err != nil {
		tool.Error(c, "参数解析失败")
	}
	service := server.MemberServer{}
	accPassLoginData := service.AccPassLogin(accPassLogin)
	//fmt.Println(accPassLoginData)
	if accPassLoginData.Id > 0 {
		//给用户创建token
		token := server.SetTingToken(accPassLoginData.Id)
		accPassLoginData.Password = ""
		accPassLoginData.Token = token
		tool.Success(c, accPassLoginData)
		return
	} else {
		tool.Error(c, "账号或密码错误")
		return
	}
}

//短信验证码登录
func (mem *MemberController) SmsLogin(c *gin.Context) {
	var smsLoginParam param.SmsLoginParam
	if err := tool.Decode(c.Request.Body, &smsLoginParam); err != nil {
		tool.Error(c, "参数解析失败")
		return
	}
	service := server.MemberServer{}
	SmsLoginData, msg := service.SmsLogin(smsLoginParam)
	//fmt.Println(SmsLoginData)
	//fmt.Println(msg)
	if SmsLoginData == nil {
		tool.Error(c, msg)
		return
	}
	SmsLoginData.Password = " "
	tool.Success(c, SmsLoginData)
}

//获取用户信息
func (mem *MemberController) MemberInfo(c *gin.Context) {
	id, ok := c.GetQuery("id")
	if !ok {
		tool.Error(c, "参数解析失败")
		return
	}
	//缓存
	value := tool.RedisGet("info" + id)
	if value != nil {
		member := model.Member{}
		uint8s, _ := value.([]uint8)
		errUint := json.Unmarshal([]byte(uint8s), &member)
		if errUint != nil {
			fmt.Println("缓存数据解析失败")
		}
		member.Password = ""
		tool.Success(c, member)
		return
	}
	//member := model.Member{}
	MemberDao := dao.MemberDao{Orm: tool.DbEngine}
	mId, _ := strconv.Atoi(id)
	memberInfo := MemberDao.GetMemberInfo(mId)
	if memberInfo.Id == 0 {
		tool.Success(c, nil)
		return
	}
	memberInfo.Password = ""
	tool.Success(c, memberInfo)
}

//修改用户数据
func (mem *MemberController) MemberEdit(c *gin.Context) {
	var member model.Member
	member.Id = c.GetInt("userId")
	member.Utime = time.Now().Unix()
	if err := tool.Decode(c.Request.Body, &member); err != nil {
		tool.Error(c, "参数解析失败")
	}
	MemberDao := dao.MemberDao{Orm: tool.DbEngine}
	memberData := MemberDao.MemberEdit(member)
	if memberData.Id == 0 {
		tool.Error(c, "修改失败")
		return
	}

	//缓存重新设置
	bytes, _ := json.Marshal(member)
	mId := strconv.Itoa(member.Id)
	tool.RedisSet("member:info:"+mId, string(bytes), 24*3600)

	member.Password = ""
	tool.Success(c, member)
}

/*
	bytes, _ := json.Marshal(member)
	mId := strconv.Itoa(member.Id)
	tool.RedisSet("member:info:"+mId, string(bytes), 24*3600)
*/

/*value := tool.RedisGet("info1")
uint8s,_ := value.([]uint8)
erruint := json.Unmarshal([]byte(uint8s), &member)
if erruint != nil{
	fmt.Println("解析失败")
}
fmt.Println(member)*/

/*fmt.Println("--------------token--start")
token := server.SetTingToken()
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
_= enc.Encode(&accPassLoginData)
//fmt.Println(buffer.Bytes())
_,setRedis := tool.RedisCon.Do("set",token,buffer.Bytes())
if setRedis != nil{
	fmt.Println("redis数据库存储失败",setRedis)
	tool.Error(c, "token 缓存失败")
	return
}
//设置key的过期时间
expireError := tool.RedisCon.Send("expire", token, 24*3600)
if expireError != nil {
	fmt.Println("----获取redis过期时间:"+token+":错误----", expireError)
	return
}
fmt.Println("--------------token--end")*/
